package com.pw.study.flink.exercise;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

import java.util.Arrays;

public class W1 {
    public static void main(String[] args) {
        exercise();
    }

    private static void exercise() {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        DataStreamSource<String> stream = env.readTextFile("data/file/words.txt");
         //mcFlatMap(stream);
        //mcMap(stream);
        //mcMap2(stream);
        mcKey(stream);
        mcSum(stream);

        //输入数据


        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void mcSum(DataStreamSource<String> stream) {
        mcKey(stream).sum(1).print();
    }

    private static KeyedStream<Tuple2<String, Integer>, String> mcKey(DataStreamSource<String> stream) {

        KeyedStream<Tuple2<String, Integer>, String> key = mcMap2(stream).keyBy(t -> t.f0);
        key.sum(1).print();
        return key;
    }

    private static SingleOutputStreamOperator<Tuple2<String, Integer>> mcMap2(DataStreamSource<String> stream) {
        SingleOutputStreamOperator<Tuple2<String, Integer>> map = mcFlatMap(stream).map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String s) throws Exception {
                return Tuple2.of(s, 1);
            }
        });
        map.print();
        return map;
    }

    private static void mcMap(DataStreamSource<String> stream) {
        stream.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public void flatMap(String value, Collector<String> out) throws Exception {
                Arrays.stream(value.split(" ")).forEach(out::collect);
            }
        }).map(word -> Tuple2.of(word, 1)).returns(Types.TUPLE(Types.STRING, Types.INT)).print();
    }

    private static SingleOutputStreamOperator<String> mcFlatMap(DataStreamSource<String> stream) {
        SingleOutputStreamOperator<String> result = stream.flatMap((FlatMapFunction<String, String>) (value, out) -> Arrays.stream(value.split(" ")).forEach(out::collect))
                .returns(Types.STRING);
        result.print();
        return result;
    }

}
